<template>
    <div>
        <el-upload action="#" list-type="picture" :multiple="false"  :show-file-list="showFileList" :file-list="fileList" 
        :on-remove="handleRemove" :on-preview="handlePreview" :http-request="uploadFile">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过10MB</div>
        </el-upload>
        <!-- 点击缩略图的弹框 -->
        <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="fileList[0].url" alt="">
        </el-dialog>
    </div>
</template>

<script>
  import {uploadFile} from '@/api/pmsApi'
  export default {
    name: 'SingleUpload',
    props: {
        value: String
    },
    computed: {
        imageUrl() {
            return this.value;
        },
        imageName() {
            if (this.value !== null && this.value !== '') {
                return this.value.substr(this.value.lastIndexOf("/") + 1);
            } else {
                return null;
            }
        },
        fileList() {
            return [{
                name: this.imageName,
                url: this.imageUrl
            }]
        },
        showFileList: {
            get: function() {
                return this.value !== null && this.value !== '' && this.value !== undefined
            },
            set: function(newValue) {

            }
        }
    },
    data() {
        return {
            dialogVisible: false
        }
    },
    methods: {
        emitInput(val) {
            this.$emit('input', val)
        },
        handleRemove(file, fileList) {
            this.emitInput('');
        },
        handlePreview(file) {
            this.dialogVisible = true;
        },
        // 上传文件的方式有两种
        // 1.先调用后端接口获取上传凭证,然后在直接调用minio接口上传
        // 2.直接调用后端接口上传
        // 第一种方案需要再验证,此处先采用第二种方案实现
        uploadFile(content) { 
            const file = content.file;
            var formData = new FormData();
            formData.append('file', file)
            uploadFile(formData).then(response => {
                let data = response.data;
                this.showFileList = true;
                this.fileList.pop();
                this.fileList.push({name: data.name, url: data.url});
                this.emitInput(this.fileList[0].url);
            });
        },
        // 当文件已经上传时,提醒先删除上传的文件
        onExceedLogo() {
            this.$message({
                message: '文件已上传,请先删除之前文件在重新上传!',
                type: 'warning'
            });
            this.logFileList = [];
            this.addBrandParam.logo = '';
        },
    }
}
</script>